<?php

namespace App\Game;

use Carbon\Carbon;
use App\Models\Inf\Player;
use App\Game\Traits\AllBetTrait;
use App\Models\Def\MainGamePlat;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use Mockery\Exception;

class allbet extends Game
{
    use AllBetTrait;

    private $platName = 'allbet';



    public function __construct()
    {

        $this->adds = [
            'main_game_plat_code' => $this->platName,
            'status' => 1
        ];
    }

    /**
     * gameapi
     * 2018/9/19 16:15
     * Administrator
     * __get
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->$key;
    }

    public function __set($key, $value)
    {
        $this->$key = $value;
    }

    public function getLength()
    {
        return $this->length;
    }

    public function getPre()
    {
        return $this->pre;
    }



    public function getSign($arr)
    {
        $arr['random'] = mt_rand();
        $real_param = http_build_query($arr);
        $data = base64_encode(allbetdes::encryptText($real_param, $this->des));
        $to_sign = $data . $this->md5;
        $sign = base64_encode(md5($to_sign, true));
        return ['sign' => $sign, 'data' => $data];
    }

    public function curlQueryHandicap()
    {
        $data = [
            'random' => mt_rand(),
            'agent' => $this->username,
        ];

        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/query_handicap";
        $params = [
            'data' => $arr['data'],
            'sign' => $arr['sign'],
            'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);

        return $output['handicaps'];
    }

    //创建用户

    public function curlCreateMember($accountUserName, $password, $request)
    {
        $random = mt_rand();
        $handicaps = $this->curlQueryHandicap();
        //获取一个VIP盘口编号
        $vipHandicaps = array_pluck(
            array_where($handicaps, function ($value) {
                return $value['handicapType'] == "1";
            }
            ), 'id'
        );
        $vipHandicaps = implode(',', array_random($vipHandicaps, 1));
        //获取三个普通盘口编号
        $orHandicaps = array_pluck(
            array_where($handicaps, function ($value) {
                return $value['handicapType'] == "0";
            }
            ), 'id'
        );
        $handicaps = implode(',', array_random($orHandicaps, 3));

        $data = [
            'random' => $random,
            'agent' => $this->username,
            'client' => $accountUserName,
            'password' => $password,
            'vipHandicaps' => $vipHandicaps,
            'orHandicaps' => $handicaps,
            'orHallRebate' => '0'
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/check_or_create";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);
        if (isset($output['client']) && $output['error_code'] == 'OK') {
            return ['success' => true, 'data' => ['accountUserName' => $accountUserName, 'password' => $password], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '创建失败'];
        }


    }

    //获取余额


    public function curlGetBalance($accountUserName)
    {
        $mainGamePlat = MainGamePlat::where('main_game_plat_name', $this->platName)->first();
        $player = Player::where([
                ['main_game_plats_id', '=', $mainGamePlat->id],
                ['username', '=', $accountUserName],
            ]
        )->first();

        $data = [
            'client' => $accountUserName,
            'password' => $player->password,
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/get_balance";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);
        if (isset($output['balance']) && $output['error_code'] == 'OK') {
            return ['success' => true, 'data' => ['balance' => $output['balance']], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '查询失败'];
        }
    }

    //转入游戏

    public function curlTransferIn($accountUserName, $price, $transferid)
    {
        $transferid = $this->propertyID . str_random(20 - strlen($this->propertyID));
        $data = [
            'agent' => $this->username,
            'sn' => $transferid,
            'client' => $accountUserName,
            'operFlag' => 1,
            'credit' => $price,
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/agent_client_transfer";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = null;
        try {
            $output = $this->request('GET', $url, $params);
        } catch (ServerException $exception) {
            if ($exception->hasResponse()) {
                $output = $exception->getResponse()->getBody()->getContents();
            }
        }
        if (empty($output)) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '未取得' . $this->platName . '响应信息'];
        }

        $output = json_decode($output, true);

        if (array_key_exists('error_code', $output)) {
            if ($output['error_code'] == 'OK') {
                return ['success' => true, 'data' => ['transferid' => $transferid, 'transfer_state' => 1], 'message' => ''];

            } else {
                return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '转账失败,' . $output['error_code']];
            }
        } else {
            return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '转帐未知'];
        }

    }

    //转出游戏
    public function curlTransferTo($accountUserName, $price, $transferid)
    {
        $transferid = $this->propertyID . str_random(20 - strlen($this->propertyID));
        $data = [
            'agent' => $this->username,
            'sn' => $transferid,
            'client' => $accountUserName,
            'operFlag' => 0,
            'credit' => $price,
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/agent_client_transfer";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = null;
        try {
            $output = $this->request('GET', $url, $params);
        } catch (ServerException $exception) {
            if ($exception->hasResponse()) {
                $output = $exception->getResponse()->getBody()->getContents();
            }
        }
        if (empty($output)) {
            return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '未取得' . $this->platName . '响应信息'];
        }
        $output = json_decode($output, true);

        if (array_key_exists('error_code', $output)) {
            if ($output['error_code'] == 'OK') {
                return ['success' => true, 'data' => ['transferid' => $transferid, 'transfer_state' => 1], 'message' => ''];

            } else {
                return ['success' => false, 'data' => ['transfer_state' => 0], 'message' => '转出失败,' . $output['error_code']];
            }
        } else {
            return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '转帐未知'];
        }

    }

    //查询订单状态
    public function curlCheckTransfer($request)
    {
        $data = [
            'sn' => $request->transferid,
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/query_transfer_state";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);
        if(array_key_exists('error_code',$output)){
            if ($output['error_code'] == "OK") {
                if(array_key_exists('transferState',$output)){
                    if($output['transferState']==1){
                        return ['success' => true, 'data' => ['transfer_state'=>1], 'message' => ''];
                    }elseif ($output['transferState']==2){
                        return ['success' => true, 'data' => ['transfer_state'=>0], 'message' => ''];
                    }
                }
            }
        }else{
            return ['success' => false, 'data' => ['transfer_state'=>-1], 'message' => $output['message']];
        }

    }

    //踢线
    public function curlKick($request)
    {
        $data = [
            'client' => $request->accountUserName,
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/logout_game";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);

        if ($output['error_code'] == "OK") {
            return ['success' => true, 'data' => [], 'message' => $output['message']];

        } else {
            return ['success' => false, 'data' => [], 'message' => $output['message']];
        }
    }

    //进入游戏
    public function curlJoinGame($request)
    {
        $mainGamePlat = MainGamePlat::where('main_game_plat_name', $this->platName)->first();
        $player = Player::where([
                ['main_game_plats_id', '=', $mainGamePlat->id],
                ['username', '=', $request->accountUserName],
            ]
        )->first();

        $data = [
            'password' => $player->password,
            'client' => $request->accountUserName,
            'targetSite' => $this->targetSitePC
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/forward_game";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);

        if (isset($output['gameLoginUrl']) && $output['error_code'] == 'OK') {
            return ['success' => true, 'data' => ['url' => $output['gameLoginUrl']], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '进入游戏失败'];
        }
    }

    public function curlJoinMobileGame($request)
    {

        $mainGamePlat = MainGamePlat::where('main_game_plat_name', $this->platName)->first();
        $player = Player::where([
                ['main_game_plats_id', '=', $mainGamePlat->id],
                ['username', '=', $request->accountUserName],
            ]
        )->first();

        $data = [
            'password' => $player->password,
            'client' => $request->accountUserName,
            'targetSite' => $this->targetSiteH5
        ];
        $arr = $this->getSign($data);
        $url = $this->gameUrl . "/forward_game";
        $params = [
            'data' => $arr['data'], 'sign' => $arr['sign'], 'propertyId' => $this->propertyID
        ];
        $output = $this->request('GET', $url, $params);
        $output = json_decode($output, true);

        if (isset($output['gameLoginUrl']) && $output['error_code'] == 'OK') {
            return ['success' => true, 'data' => ['url' => $output['gameLoginUrl']], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '进入游戏失败'];
        }
    }


    //游戏抓单
    public function curlGetBetRecord(Carbon $startTime, Carbon $endTime)
    {
        $diffMinutes = $startTime->diffInMinutes($endTime, false);
        if ($diffMinutes < 23 * 59 + 59) {
            $times = $this->parseTimeInterval($startTime, $endTime);
            return $this->getBetRecordPieceOf($times);
        } else {
            return $this->getBetRecordInDays($startTime);
        }

    }


}